<template>
  <!-- 载入席位时间预设 -->
  <el-dropdown @command="loadSeatPlan">
    <el-button type="primary" link>
      <span>载入席位预设</span>
      <el-icon><i-ep-arrow-down /></el-icon>
    </el-button>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item
          v-for="(item, index) in seatPlans"
          :command="index"
          :disabled="item.disabled"
          >{{ item.name }}</el-dropdown-item
        >
      </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>

<script setup>
import usePlanningStore from "@/stores/planningStore";
import seatPlans from "@/profiles/seatPlans.json";
import dayjs from "dayjs";

const planningStore = usePlanningStore();

const loadSeatPlan = (index) => {
  if (seatPlans && index <= seatPlans.length && seatPlans[index]) {
    // 设置过滤orgId与当前预设的orgId一致
    planningStore.selectedOrgId = seatPlans[index].orgId;
    // 设置是否复制后续时段的席位为false
    planningStore.isSeatSlotsCopyFollowings = false;
    for (let j = 0; j < planningStore.timeSlots.length; j++) {
      const slot = planningStore.timeSlots[j];
      let slotStart = dayjs(slot.from);
      let slotEnd = dayjs(slot.to);
      // 先清空所有值班时段的席位
      slot.seats = [];
      for (let i = 0; i < seatPlans[index].content.length; i++) {
        const seat = seatPlans[index].content[i];
        for (
          let k = 0;
          k < seatPlans[index].content[i].defaultTimes.length;
          k++
        ) {
          const time = seatPlans[index].content[i].defaultTimes[k];
          const [startHour, startMinute] = time.from.split(":");
          const [endHour, endMinute] = time.to.split(":");
          let seatStart = slotStart
            .hour(parseInt(startHour))
            .minute(parseInt(startMinute));
          let seatEnd = slotEnd
            .hour(parseInt(endHour))
            .minute(parseInt(endMinute));
          if (seatEnd.isBefore(seatStart)) {
            seatEnd = seatEnd.add(1, "day");
          }
          if (
            slotStart.isSameOrBefore(seatEnd) &&
            seatEnd.isSameOrAfter(seatEnd)
          ) {
            slot.seats.push(seat.name);
          }
        }
      }
    }
  }
};

const loadDefaultSeatPlan = () => {
  loadSeatPlan(0);
};

onMounted(() => {
  loadDefaultSeatPlan();
});
</script>

<style scoped>
.el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}
</style>
